package com.lilosoft.business.util;

import com.lilosoft.core.cache.JedisRepository;
import com.lilosoft.core.utils.commons.DateUtils;
import com.lilosoft.core.utils.commons.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description: 生成劈批次号公共类
 * User: 小峰
 * Date: 2019-08-30
 * Time: 13:54
 */
@Component
public class PreInitCdBatchUtil {
    @Autowired
    private JedisRepository jedisRepository;

    //过期时间 一天有效
    private Integer EXPIRE_TIME = 24 * 60 * 60 - 1;

    private String DATE_KEY =null;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 生成批次号
     *
     * @return
     */
    public String initCdBatch() {
        DATE_KEY= DateUtils.formatDate(new Date(), "yyyyMMdd");
        try {
            String dateKeyCount = DATE_KEY + "count";
            if (jedisRepository.exists(0, dateKeyCount)) {
                String redisCacheValue = jedisRepository.getObjectValue(0, dateKeyCount) + "";
                if (StringUtils.length(redisCacheValue) < 5) {
                    redisCacheValue = StringUtils.leftPad(redisCacheValue, 5, "0");
                }
                return DATE_KEY + redisCacheValue;
            } else {
                jedisRepository.SetStringValue(dateKeyCount, "1", EXPIRE_TIME);
                return DATE_KEY + "00001";
            }
        } catch (Exception ex) {
            logger.error("调用Redis出现错误,信息:"+ex.getMessage());
            return DATE_KEY + "00001";
        }
    }

    /**
     * 同步的标识增加
     */
    public void addCdBatch() {
        DATE_KEY= DateUtils.formatDate(new Date(), "yyyyMMdd");
        try {
            String dateKeyCount = DATE_KEY + "count";
            if (jedisRepository.exists(0, dateKeyCount)) {
                jedisRepository.incr(0, dateKeyCount, EXPIRE_TIME);
            } else {
                jedisRepository.SetStringValue(dateKeyCount, "1", EXPIRE_TIME);
            }
        } catch (Exception ex) {
            logger.error("调用Redis出现错误,信息:"+ex.getMessage());
        }

    }


}
